// base
import Taro, { Component } from '@tarojs/taro'
import { View, Text, Image } from '@tarojs/components'
import { AtActionSheet } from 'taro-ui'
// redux
import { connect } from '@tarojs/redux'
import { DOREQUESTSETTINGPAGE } from './store/actions/pagesettingpage'
import { UPDATEPAGESETTINGPAGE } from './store/types/pagesettingpage'
import { UPDATEUSERINFO } from '../../store/types/userinfo'
import { UPDATEIM } from '../../store/types/im'
// less
import './index.less'

// componnet
import { applyCompany } from '../../service/org-company-controller'
import { redirectTo, switchTab, navigateTo } from '../../crossplatform/apiservice/navigate'
import pagejumplist from '../../configuration/pagejumplist.json'
import SwitchRole from '../../components/page-components/switch-role/index'
import { judgeLoginStatus } from '../../util/login_status'
import judgeBlack from '../../util/judge_black'

const mapActiontoProps = dispatch => ({
  updateState(payload) {
    dispatch({
      type: UPDATEPAGESETTINGPAGE,
      payload: {
        ...payload
      }
    })
  },
  updateImState(payload) {
    dispatch({
      type: UPDATEIM,
      payload: {
        ...payload
      }
    })
  },
  updateUserState(payload) {
    dispatch({
      type: UPDATEUSERINFO,
      payload: {
        ...payload
      }
    })
  },
  dorequest() {
    return new Promise(resolve => {
      let promise = DOREQUESTSETTINGPAGE()
      dispatch(promise)
      promise.payload.then(data => {
        resolve(data)
      })
    })
  }
})

@connect(
  ({ pagesettingpage, im, userinfo }) => ({
    ...pagesettingpage,
    ...userinfo,
    ...im
  }),
  mapActiontoProps
)
class SettingPage extends Component {
  config = {
    navigationBarTitleText: '设置'
  }

  constructor(props) {
    super(props)
    this.state = {
      modalVisible: false
    }
  }

  componentWillMount() {
    // onLoad
  }

  componentDidMount() {
    // onready
  }

  componentDidShow() {
    // onshow
  }

  componentDidHide() {
    // onhide
  }

  componentWillUnmount() {
    // onUnload
  }

  queryWrap = () => {
    this.props.dorequest()
  }

  changeUserRole = () => {
    this.setState({
      modalVisible: true
    })
  }

  onOk = () => {
    const { role } = this.props
    if (role == 'personal') {
      // 调用接口 判断是否有B端身份  有: 跳转到我的页面 成功修改身份 无: 跳转到资料页/公司选择页
      const { userId } = this.props
      // 获取用户创建公司信息
      applyCompany({ userId }).then(({ data }) => {
        const { entry = {} } = data
        switch (entry.checkStatus) {
          case 0:
            switch (entry.type) {
              case 'company':
                // 如果用户有 则跳转创建公司页面
                navigateTo({
                  url: `${pagejumplist['create-new-cp'].path}?checkReason=${entry.checkReason}&tianYanChaId=${entry.tianYanChaId}&licenseUrl=${entry.licenseUrl}&name=${entry.companyName}&checkStatus=${entry.checkStatus}&companyId=${entry.companyId}`
                })
                break
              case 'operator':
                // 加入申请 申请拒绝
                redirectTo({
                  url: `${pagejumplist['join-new-cp'].path}?id=${entry && entry.companyId}&name=${
                    entry.companyName
                  }&status=${entry.checkStatus}`
                })
                break
              default:
                break
            }
            break
          case 1:
            // 加入申请审批通过(正常状态)  跳转到我的页面 成功修改身份
            let companyId = entry.companyId
            judgeBlack.getBlackCompanyIds(companyId, true).then(isBlack => {
              if (!isBlack) {
                if (companyId) {
                  this.props.updateUserState({
                    role: 'company',
                    companyId
                  })
                } else {
                  this.props.updateUserState({
                    role: 'company'
                  })
                }
                this.props.updateImState({
                  contactList: []
                })
                switchTab({
                  url: pagejumplist['self-center'].path
                })
              }
            })
            break
          case 2:
            // 申请中
            switch (entry.type) {
              case 'company':
                // 如果用户有 则跳转创建公司页面
                navigateTo({
                  url: `${pagejumplist['create-new-cp'].path}?checkReason=${entry.checkReason}&tianYanChaId=${entry.tianYanChaId}&licenseUrl=${entry.licenseUrl}&name=${entry.companyName}&checkStatus=${entry.checkStatus}&companyId=${entry.companyId}`
                })
                break
              case 'operator':
                navigateTo({
                  url: `${pagejumplist['join-new-cp'].path}?id=${entry && entry.companyId}&name=${
                    entry.companyName
                  }&status=${entry.checkStatus}`
                })
                break
              default:
                break
            }
            break
          default:
            // 都没有 则跳转资料页
            judgeLoginStatus({ parmas: 'type=b' })
            break
        }
      })
    } else {
      this.props.updateUserState({
        role: 'personal'
      })
      this.props.updateImState({
        contactList: []
      })
      let timer = setTimeout(() => {
        clearTimeout(timer)
        switchTab({
          url: pagejumplist['self-center'].path
        })
      }, 500)
    }
    this.onCancel()
  }

  onCancel = () => {
    this.setState({
      modalVisible: false
    })
  }

  confirmSwitchRole = () => {
    this.onCancel()
    this.onOk()
  }

  render() {
    const { role } = this.props
    const { modalVisible } = this.state
    return (
      <View className="SettingPage_id44162">
        <View className="list-item">
          <View className="item-title">提醒设置</View>
          <View className="item-desc">
            <Image
              className="item-arrow"
              src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
            />
          </View>
        </View>
        <View className="list-item">
          <View className="item-title">我要评价</View>
          <View className="item-desc">
            <Image
              className="item-arrow"
              src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
            />
          </View>
        </View>
        <View className="list-item">
          <View className="item-title">帮助反馈</View>
          <View className="item-desc">
            <Image
              className="item-arrow"
              src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
            />
          </View>
        </View>
        <View className="list-item">
          <View className="item-title">关于我们</View>
          <View className="item-desc">
            <Image
              className="item-arrow"
              src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
            />
          </View>
        </View>

        <View className="list-item margin-top-80" onClick={this.changeUserRole}>
          <View className="item-title">切换身份</View>
          <View className="item-desc">
            <Text>{role == 'company' ? '求职者' : '招聘者'}</Text>
            <Image
              className="item-arrow"
              src="https://imagesize.hrwork.com/sp/files/8db9c17d-2da7-4a9e-a44c-98a32670fcc7.png"
            />
          </View>
        </View>

        <AtActionSheet isOpened={modalVisible}>
          <SwitchRole role={role} onConfirm={this.confirmSwitchRole} />
        </AtActionSheet>
      </View>
    )
  }
}

export default SettingPage
